import { ref } from 'vue';
import { getInitInfo,type AppInitInfo } from '@/common/request/api'
import { defineStore } from 'pinia'
import {rgbToHex} from '@/common/utils'

import type { AppContext } from '@/common/hooks'

export type Skin = {
	type: string,
	primary: string,
	gradientPrimary: string
}

type SkinMap = {
	red: Skin,
	orange: Skin,
	green: Skin,
	gold: Skin,
	blue: Skin,
	green_light_1: Skin
	blue_light_1: Skin
	black_light_1: Skin
	pink_light_1: Skin,
	green_light_2: Skin,
	purple: Skin,
	brown: Skin,
}

export type SkinKey = keyof SkinMap
const skinMap: SkinMap = {
	red: {
		primary: 'rgba(245, 34, 45, 1)',
		gradientPrimary: 'linear-gradient(45deg, #F5222D 0%, #FF8F8B 100%)',
		type: 'red'
	},
	orange: {
		primary: 'rgba(254,92,21, 1)',
		gradientPrimary: 'linear-gradient(90deg, #FE5C15 0%, #FEAA58 100%)',
		type: 'orange'
	},
	green: {
		primary: 'rgba(41,215,182, 1)',
		gradientPrimary: 'linear-gradient(90deg, #29D7B6 0%, #25E68C 100%)',
		type: 'green'
	},
	gold: {
		primary: 'rgba(244,204,148, 1)',
		gradientPrimary: 'linear-gradient(270deg, #F4CC94 0%, #D9AB6F 100%)',
		type: 'gold'
	},
	blue: {
		primary: 'rgba(132,165,255, 1)',
		gradientPrimary: 'linear-gradient(270deg, #84A5FF 0%, #2E54EB 100%)',
		type: 'blue'
	},
	green_light_1: {
		primary: 'rgba(97, 183, 0, 1)',
		gradientPrimary: 'linear-gradient(270deg, #C3EB7C 0%, #61B700 100%)',
		type: 'green_light_1'
	},
	blue_light_1: {
		primary: 'rgba(73, 173, 223, 1)',
		gradientPrimary: 'linear-gradient(270deg, #80D6F1 0%, #49ADDF 100%)',
		type: 'blue_light_1'
	},
	black_light_1: {
		primary: 'rgba(241, 90, 36, 1)',
		gradientPrimary: 'linear-gradient(270deg, #F15A24 0%, #F9934A 100%)',
		type: 'black_light_1'
	},
	pink_light_1: {
		primary: 'rgba(249, 58, 111, 1)',
		gradientPrimary: 'linear-gradient(90deg, #F93A6F 0%, #FE74AB 100%)',
		type: 'pink_light_1'
	},
	green_light_2: {
		primary: 'rgba(8, 171, 132, 1)',
		gradientPrimary: 'linear-gradient(90deg, #08AB84 0%, #06A17C 100%)',
		type: 'green_light_2'
	},
	purple: {
		primary: 'rgba(107, 77, 250, 1)',
		gradientPrimary: 'linear-gradient(180deg, #BD50F4 0%, #6B4DFA 100%)',
		type: 'purple'
	},
	brown: {
		primary: 'rgba(142, 110, 82, 1)',
		gradientPrimary: 'linear-gradient(180deg, #DBB591 0%, #8E6E52 100%)',
		type: 'brown'
	},
}

export type TabbarPageItem = {
	bgcolor?: string
	isDefault: 'Y' | 'N'
	pageDesc: string
	pageId: number
	pageName: string
	pageType: number
	templateId: number
	text: {
		pageId: number,
		pageLayout: string
	}
	pageLayout?:string
}

export type TabbarItem = {
	index: number
	custom: boolean
	link: {
		type: number
		pageUrl: string
	},
	text: string,
	iconPath: string,
	selectedIconPath: string
	
}

type LayoutTabbarItem = TabbarItem&{
	default_img: string
	active_img: string
	icon:string
}



type UnionKeys<T> = T extends T ? keyof T : never;
// 传入两个类型，将第二个类型上的属性均设置为可选，返回两个类型的联合
type StrictUnionHelper<T, TAll> =
    T extends any
    ? T & Partial<Record<Exclude<UnionKeys<TAll>, keyof T>, never>> : never;

export type pageLink = {
	pageName:string
	linkName:string
	pageUrl:string
	linkUrl:string
	pageType?:1|2|4
	isOther?:boolean
	mpType:undefined
	appId:undefined
	path:undefined
	isMp:undefined
}|{
	pageName:string
	linkName:string
	pageUrl:undefined
	linkUrl:undefined
	pageType:undefined
	isOther:undefined
	mpType:number
	appId:string
	path:string
	isMp:boolean
}|{
	pageName:string
	linkName:string
	pageUrl:undefined
	linkUrl:undefined
	pageType:undefined
	isOther:undefined
	mpType:undefined
	appId:undefined
	path:undefined
	isMp:undefined
	appSystemApiType:number,
	isAppSystemApi: boolean
}

export type SplashOption = {
	open: boolean,
	openType: 1|2,
	timing: number,
	showCount: number,
	showType: 1|2,
	imgList: {
			url: string,
			link: pageLink
		}[]
}






const getOrderIconText = (pages: Array<TabbarPageItem>) => {
	let userPage = pages.find(item => item.pageType == 2)
	let orderIcon = JSON.parse(userPage?.text?.pageLayout || '').find((item: any) => item.componentsName === 'orderIcon')
	if (orderIcon && orderIcon.titleList) {
		return orderIcon.titleList as string[]
	}
	return []
}

// 将rgb颜色转成hex
const colorRGB2Hex = (color: string) => {
	var rgb = color.split(',');
	var r = parseInt(rgb[0].split('(')[1]);
	var g = parseInt(rgb[1]);
	var b = parseInt(rgb[2].split(')')[0]);

	var hex = "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
	return hex;
}
const setPrimary = (primary: string) => {
	getApp<any>().globalData.cssPrimaryColor = colorRGB2Hex(primary)
}

export const useInit = defineStore('init', () => {
	// 装修的模板id
	const templateId = ref('')
	// 装修的主题
	const AppSkin = ref<Skin>(uni.getStorageSync('app_skin') || {
		type: '',
		primary: 'rgba(255, 255, 255, 1)',
		gradientPrimary: 'linear-gradient(45deg, #fff 0%, #fff 100%)'
	})
	// 装修的tabbar页面数据
	const tabbarPage = ref<[TabbarPageItem, TabbarPageItem, TabbarPageItem] | []>([])
	// tabbar的聚焦与未聚焦时，文本颜色配置
	const tabbarOption = ref<TabbarOption>({
		inactiveColor: '#808080',
		activeColor: '',
		bgColor:'',
		style:1
	})
	// 自定义tabbar的数据
	const tabbarData = ref<TabbarItem[]>([])
	// 普通页面或可视化的组件要跳转到指定tabbar页时，将tabbarPageIndex修改为要跳转的tabbar页对应的索引，tabbar将切换至对应的页面
	const tabbarPageIndex = ref(0)
	
	const setTabbarPageIndex = (index:number) => {
		tabbarPageIndex.value = index
	}

	const hasTabbarPage = (tabbarUrl: string) => {
		let page = tabbarData.value.findIndex(item => item.link.pageUrl && item.link.pageUrl === tabbarUrl)
		return page
	}

	// 装修的订单按钮文本配置
	const orderIconText = ref<string[]>([])
	// 是否正在加载装修数据
	const pageLoading = ref(false)
	// 装修的启动页配置
	const splashOption = ref({
		open: false,
		openType: 1,
		timing: 3,
		showCount: 0,
		showType: 1,
		imgList: [
			{
				url: '',
				link: {
					linkName: '',
					linkUrl: '',
					pageUrl:'',
					isOther:false
				}
			}
		]
	})


	// 是否开启退款功能
	const isRefund = ref(false)
	// 是否配置了地图api的key
	const hasMapKey = ref(false)
	const setHasMapKey = (state: boolean) => {
		hasMapKey.value = state
	}


	const setSkin = (key: SkinKey) => {
		AppSkin.value = skinMap[key]
		setPrimary(AppSkin.value.primary)
		uni.setStorageSync('app_skin', AppSkin.value)
	}

	const getAppConfig = async (isRefresh = false) => {
		pageLoading.value = isRefresh
		let params: any = {}
		// #ifdef H5
		let hash = window.location.hash.split("?")[1]
		if (hash) {
			try {
				params = JSON.parse(
					'{"' +
					decodeURI(hash)
						.replace(/"/g, '\"')
						.replace(/&/g, '","')
						.replace(/=/g, '":"') +
					'"}'
				);
			} catch (e) {
				params = {}
			}

		}
		if (params?.templateId) {
			// #ifdef  PREVIEW
			uni.setStorageSync('templateId', params.templateId)
			templateId.value = params.templateId
			// #endif
		} else {
			uni.removeStorageSync('templateId')
		}
		// #endif
		const res = await getInitInfo({ templateId: params?.templateId })
		tabbarPage.value = res.pages
		orderIconText.value = getOrderIconText(res.pages)
		pageLoading.value = false
		splashOption.value = JSON.parse(res.start.layout||"{}")
		isRefund.value = res.isRefund === 'true'
		setSkin(res.globalBg)

		return res
	}

	const setTabbarData = (ctx: AppContext, res:AppInitInfo) => {
		// 设置底部导航栏
		let _tabbarData:TabbarItem[] = []
		// #ifdef PRIVATE
		let icon = [{ text: ctx.$t('tabbar.首页'), pageUrl: 'home', icon: 'icon-shouye' }, { text: ctx.$t('tabbar.分类'), pageUrl: 'classify', icon: 'icon-a-fenlei1' }, { text: ctx.$t('tabbar.购物车'), pageUrl: 'cart', icon: 'icon-a-gouwuche1' }, { text: ctx.$t('tabbar.个人中心'), pageUrl: 'userInfo', icon: 'icon-wode' }]
		icon.forEach((item, index) => {
			let data = {
				index,
				custom: false,
				link: { type: 2, pageUrl: item.pageUrl },
				text: item.text,
				iconPath: item.icon,
				selectedIconPath: item.icon
			}
			_tabbarData.push(data)
		})
		// #endif
		// #ifndef PRIVATE
		let inactiveColor = res.bottomMenus.cssDefault ? res.bottomMenus.cssDefault.replace(/(?:\(|\)|rgba)*/g, '').split(',') : []
		let activeColor = res.bottomMenus.cssSelect ? res.bottomMenus.cssSelect.replace(/(?:\(|\)|rgba)*/g, '').split(',') : []
		tabbarOption.value = {
			inactiveColor: inactiveColor.length > 3 ? rgbToHex(`rgb(${inactiveColor[0]},${inactiveColor[1]},${inactiveColor[2]})`) : '',
			activeColor: activeColor.length > 3 ? rgbToHex(`rgb(${activeColor[0]},${activeColor[1]},${activeColor[2]})`) : '',
			bgColor: res.bottomMenus.cssBg||'',
			style: res.bottomMenus.cssClass
		}

		let list = JSON.parse(res.bottomMenus.layout) as LayoutTabbarItem[]
		list.forEach((item, index) => {
			let data = {
				...item,
				index,
				text: item.text,

			}
			if (item.custom) {
				data['iconPath'] = ctx.$fullLink(item.default_img)
				data['selectedIconPath'] = ctx.$fullLink(item.active_img)
			} else {
				data['iconPath'] =item.icon
				data['selectedIconPath'] = item.icon
			}
			_tabbarData.push(data)
		})
		// #endif
		tabbarData.value = _tabbarData
	}


	interface TabbarOption {
		inactiveColor:string,
		activeColor:string,
		bgColor?:string,
		style:number
	}

	const setTabbarOption = (data:TabbarOption) => {
		tabbarOption.value = data
	}
	
	const setTabbar = (data:TabbarItem[]) => {
		tabbarData.value = data
	}


	return {
		AppSkin,
		tabbarPage,
		tabbarOption,
		tabbarData,
		tabbarPageIndex,
		setTabbarPageIndex,
		hasTabbarPage,
		orderIconText,
		pageLoading,
		splashOption,
		isRefund,
		hasMapKey,
		setHasMapKey,
		setSkin,
		getAppConfig,
		setTabbarData,
		setTabbarOption,
		setTabbar
	}
})
